/*
 * @Author: your name
 * @Date: 2020-06-05 10:38:08
 * @LastEditTime: 2020-06-05 15:00:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \IM_Web\im_web\src\axios.js
 */
import axios from 'axios'
import router from './router'
import QS from 'qs'
// import { Message } from 'element-ui'
// 创建axios实例
const service = axios.create({
    timeout: 120000,
    retry: 4,
    retryDelay: 1000
})
// 添加request拦截器
service.interceptors.request.use(config => {
    config.withCredentials = true // 允许携带token ,这个是解决跨域产生的相关问题
    let token = sessionStorage.getItem('t')
    // ////console.log()
    if (token && token !== '' && token !== 'undefined') { 
        // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
        config.headers.Authorization = token
    }
    // ////console.log(config)
    if (config.method == 'post') {
        config.data = QS.stringify(config.data) // 防止post请求参数无法传到后台
        // //////console.log(config.data)
    }
    return config
}, error => {
    Promise.reject(error)
})
// 添加respone拦截器
service.interceptors.response.use(response => {
    let res = {}
    // ////console.log('response', response)
    res.status = response.status
    res.data = response.data
    // //console.log(res)

    // if (res.data.errno == '999') {
    //     Message.closeAll();
    //     Message({
    //         message:res.data.errmsg,
    //         type:'error'
    //     })
    //     sessionStorage.clear()
    //     router.push('/login')
    //     // alert(res.data.errmsg)
    //     return false
    // }
    if (res.data.errno == '1000011') {
        // Message.closeAll()
        // Message({
        //     message: res.data.errmsg,
        //     type: 'error'
        // })
        this.$Message.destroy()
        this.$Message.error(res.data.errmsg)
        sessionStorage.clear()
        router.push('/login')
        // alert(res.data.errmsg)
        return 
    }
    return response
}, error => {
    if (error.code == 'ECONNABORTED' && error.message.indexOf('timeout') != -1) {
        var config = error.config
        config.__retryCount = config.__retryCount || 0
        if (config.__retryCount >= config.retry) {
            // Reject with the error
            // window.location.reload();
            return Promise.reject(error)
        }
        // Increase the retry count
        config.__retryCount += 1
        // Create new promise to handle exponential backoff
        var backoff = new Promise(function (resolve) {
            setTimeout(function () {
                // ////console.log('resolve');
                resolve()
            }, config.retryDelay || 1)
        })
        return backoff.then(function () {
            return axios(config)
        })
    } else {
        return Promise.reject(error)
    }
})
// service.interceptors.response.use(
//         response => {
//             let res = {}
//                 // ////console.log('response', response)
//             res.status = response.status
//             res.data = response.data
//             ////console.log(res)
//             if (res.data.errmsg == 'Expired token') {
//                 // this.$message.error('请登录！')
//                 router.push('/login')
//                 return false
//             }
//             return res
//         },
//         error => {
//             if (error.response && error.response.status == 404) {
//                 router.push('/login')
//             }
//             return Promise.reject(error.response)
//         }
//     )
// 封装get请求
export function get(url, params = {}) {
    // params.t = new Date().getTime(); //get方法加一个时间参数,解决ie下可能缓存问题.
    return service({
        url: url,
        method: 'get',
        headers: {},
        params
    })
}

// 封装post请求
export function post(url, data = {}) {
    // 默认配置
    let sendObject = {
        url: url,
        method: 'post',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json;charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json;charset=utf-8'
        },
        // emulateJSON: true,
        data: QS.stringify(data)
    }
    // ////console.log(data.secret)
    sendObject.data = data
    return service(sendObject)
}

// 封装put方法 (resfulAPI常用)
export function put(url, data = {}) {
    return service({
        url: url,
        method: 'put',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json;charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json;charset=utf-8'
        },
        data: QS.stringify(data)
    })
}
// 删除方法(resfulAPI常用)
export function deletes(url, data = {}) {
    return service({
        url: url,
        method: 'delete',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            // 'Content-Type': 'application/json;charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json;charset=utf-8'
        },
        data: QS.stringify(data)
    })
}

// 不要忘记export
export {
    service
}
